package com.yj.auto.helper;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.jfinal.log.Log;
import com.xiaoleilu.hutool.date.DateUtil;
import com.yj.auto.Constants;
import com.yj.auto.core.base.online.SessionUser;
import com.yj.auto.core.base.online.SessionUserUtil;
import com.yj.auto.core.web.log.model.AccessLog;
import com.yj.auto.core.web.log.model.LoginLog;
import com.yj.auto.core.web.log.model.ReadingLog;
import com.yj.auto.core.web.log.model.ScheduleLog;
import com.yj.auto.core.web.log.service.AccessLogService;
import com.yj.auto.core.web.log.service.LoginLogService;
import com.yj.auto.core.web.log.service.ReadingLogService;
import com.yj.auto.core.web.log.service.ScheduleLogService;
import com.yj.auto.utils.NetUtil;

public class LogHelper {
	private static final Log logger = Log.getLog(LogHelper.class);

	public static LoginLogService getLoginLogService() {
		return AutoHelper.getService("loginLogSrv");
	}

	public static AccessLogService getAccessLogService() {
		return AutoHelper.getService("accessLogSrv");
	}

	public static ReadingLogService getReadingService() {
		return AutoHelper.getService("readingLogSrv");
	}

	public static ScheduleLogService getScheduleLogService() {
		return AutoHelper.getService("scheduleLogSrv");
	}

	/**
	 * 用户登录日志
	 * 
	 * @param request
	 */
	public static void addLoginLog(HttpServletRequest request) {
		try {
			SessionUser su = SessionUserUtil.getSessionUser(request);
			if (null == su)
				return;
			LoginLog log = new LoginLog();
			log.setUserId(su.getId());
			log.setUserCode(su.getCode());
			log.setUserName(su.getName());
			log.setLoginTime(DateUtil.date());
			log.setClientIp(NetUtil.getRemoteAddr(request));
			log.setServerIp(NetUtil.getLocalhostStr());
			log.setSessionId(request.getSession().getId());
			log.setCookieId(NetUtil.getCookieString(request, Constants.SYS_COOKIE_KEY));
			log.setChannel(request.getHeader(Constants.ACCESS_CHANNEL_ID_KEY));// 渠道
			log.setPlatform(request.getHeader(Constants.ACCESS_PLATFORM_KEY));// 平台（Pc、H5）
			log.save();
		} catch (Exception e) {
			logger.error("add login log failed ", e);
		}
	}

	/**
	 * 用户退出日志
	 * 
	 * @param sessionId
	 */
	public static void addLogoutLog(String sessionId) {
		try {
			getLoginLogService().updateLogout(sessionId);
		} catch (Exception e) {
			logger.error("add logout log failed ", e);
		}
	}

	/**
	 * 访问日志
	 * 
	 * @param request
	 */
	public static void addAccessLog(HttpServletRequest request) {
		try {
			SessionUser su = SessionUserUtil.getSessionUser(request);
			if (null == su)
				return;
			AccessLog log = new AccessLog();
			log.setUserId(null == su ? null : su.getId());
			log.setUserCode(null == su ? "" : su.getCode());
			log.setUserName(null == su ? "" : su.getName());
			log.setClientIp(NetUtil.getRemoteAddr(request));
			log.setServerIp(NetUtil.getLocalhostStr());
			log.setSessionId(request.getSession().getId());
			log.setUa(request.getHeader("user-agent"));
			log.setCookieId(NetUtil.getCookieString(request, Constants.SYS_COOKIE_KEY));
			log.setChannel(request.getHeader(Constants.ACCESS_CHANNEL_ID_KEY));// 渠道
			log.setPlatform(request.getHeader(Constants.ACCESS_PLATFORM_KEY));// 平台（Pc、H5）
			log.setReferer("");// 页面跳转来源
			log.setUri(NetUtil.getRequestUri(request));
			log.setQueryString(request.getQueryString());
			Map paramMap = request.getParameterMap();
			if (null != paramMap) {
				log.setParamsMap(JSON.toJSONString(paramMap));
			}
			log.setAccessTime(DateUtil.date());
			log.save();
		} catch (Exception e) {
			logger.error("add access log failed ", e);
		}
	}

	public static void addScheduleLog(Integer scheduleId, Date stime, Date etime, boolean success, String remark) {
		try {
			ScheduleLog log = new ScheduleLog();
			log.setScheduleId(scheduleId);
			log.setStime(stime);
			log.setEtime(etime);
			long spent = etime.getTime() - stime.getTime();// 耗时（毫秒）
			log.setSpent(spent);
			log.setState(success ? "01" : "02");
			log.setServerIp(NetUtil.getLocalhostStr());
			log.setRemark(remark);
			log.save();
		} catch (Exception e) {
			logger.error("add schedule log failed ", e);
		}
	}

	/**
	 * 添加阅读记录
	 * 
	 * @param request
	 */
	public static void addReadingLog(Integer userId, Integer dataId, String dataType) {
		try {
			ReadingLog log = new ReadingLog();
			log.setUserId(userId);
			log.setType(dataType);
			log.setDataId(dataId);
			log.setReadTime(DateUtil.date());
			log.save();
		} catch (Exception e) {
			logger.error("add reading log failed ", e);
		}
	}

	/**
	 * 删除阅读记录
	 * 
	 * @param dataType
	 * @param dataId
	 */
	public static void delReadingLog(String dataType, Integer... dataId) {
		getReadingService().delete(dataType, dataId);
	}
}
